#  socketio
import asyncio
import datetime
import socketio

# fastapi
from fastapi import FastAPI, WebSocket, Request, WebSocketDisconnect
from fastapi.responses import RedirectResponse, HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.openapi.docs import get_swagger_ui_html
from fastapi.templating import Jinja2Templates
from fastapi.middleware.cors import CORSMiddleware

# settings
from settings.settings import settings

# agv socket and front socket
from sockets.agvsocket import AgvSocket
from sockets.frontsocket import sio

# events
from events.status import init_status_event
from events.control import init_control_event
from events.config import init_config_event

# 引入路由
from routes.status import status_router
from routes.config import config_router
from routes.control import control_router
from routes.navigate import navigate_router
from routes.other import other_router
from routes.base import base_router

# scheduler
from timers.scheduler import MyScheduler

# docs_url一定要设置成None,才会使用本地的 swagger-ui 的静态文件
app = FastAPI(docs_url=None)

# socketio
app.mount("/ws", socketio.ASGIApp(sio))
app.mount("/static", StaticFiles(directory="static"), name="static")


app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


# 初始化 agv socket
flag = AgvSocket().init_socket_pool()
if flag:
    print('server-->agv,success!!!')
else:
    print('server-->agv,fail!!!')


@app.on_event("startup")
async def start_database():
    # 启动定时器
    MyScheduler().start()
    # 前面启动定时器,添加向定时器中添加事件
    await init_status_event()
    await init_control_event()
    await init_config_event()


# docs文档
@app.get("/", tags=["Docs"])
async def get_docs():
    return RedirectResponse("/docs")


# docs
@app.get("/docs", include_in_schema=False)
async def custom_swagger_ui_html():
    return get_swagger_ui_html(
        openapi_url=app.openapi_url,
        title=app.title + " - Swagger UI ",
        oauth2_redirect_url=app.swagger_ui_oauth2_redirect_url,
        swagger_js_url="/static/swagger-ui/swagger-ui-bundle.js",
        swagger_css_url="/static/swagger-ui/swagger-ui.css",
        swagger_favicon_url="/static/swagger-ui/favicon.png",
    )


# 关于agv本身的一些router
app.include_router(status_router, tags=["Status"], prefix="/status")
app.include_router(config_router, tags=["Config"], prefix="/config")
app.include_router(control_router, tags=["Control"], prefix="/control")
app.include_router(navigate_router, tags=["Navigate"], prefix="/navigate")
app.include_router(other_router, tags=["Other"], prefix="/other")

# 关于后端服务的一些基本的router,比如重连agv,启动定时任务计划
app.include_router(base_router, tags=["Base Control"], prefix="/base")
